import Vue from 'vue'

import VueRouter from 'vue-router'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
import Detail from '@/pages/Detail'
import home from '@/pages/Home'
import search from '@/pages/Search'
import login from '@/pages/Login'
import register from '@/pages/Register'
import Addcartsuccess from '@/pages/AddCartSuccess'
import shopCart from '@/pages/ShopCart'
import pay from '@/pages/Pay'
import paysuccess from '@/pages/PaySuccess'
import trade from '@/pages/Trade'
const center=()=>{
    return import('@/pages/Center')
}

let router = new VueRouter({
    routes:[
        {
            path:'/home',
            component:home,
            meta:{show:true}
        },
        {
            path:'/search/:keyword?',
            component:search,
            name:'search',
            meta:{show:true}
        },
        {
            path:'/login',
            component:login,
            meta:{show:false}
        },
        {
            path:'/register',
            component:register,
            meta:{show:false}
        },
        {
            path: "/",
            redirect: "/home"
        },
        {
            path:'/detail/:skuid?',
            component:Detail,
            name:"detail",
            meta:{show:true}
        },
        {
            path: "/addcartsuccess",
            name: 'addcartsuccess',
            component: Addcartsuccess,
            meta: { show: true }
        },
        {
            path: "/shopcart",
            name: 'shopcart',
            component: shopCart,
            meta: { show: true }
        },
        {
            path: "/pay",
            component: pay,
            meta: { show: true }
        },
        {
            path: "/paysuccess",
            component: paysuccess,
            meta: { show: true }
        },
        {
            path: "/trade",
            component: trade,
            meta: { show: true }
        },
        {
            path: "/center",
            component: center,
            meta: { show: true }
        },
    ],
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})

router.beforeEach((to,from,next)=>{
   next();
let token = localStorage.getItem('token');
if (token) {
    if (to.path =='/login'||to.path =='/register') {
        next('/home');
    }
}else{
    next();
    if (to.path=='/addcartsuccess') {
        alert('请注册或登录，再加入购物车')
        next('/login');
    }else if (to.path=='/shopcart'){
        alert('请注册或登录，再加入购物车')
        next('/login');
    }else if(to.path=='/center'){
        alert('请注册或登录，再加入购物车')
        next('/login');
    }
    else if(to.path=='/trade'){
        alert('请注册或登录，再加入购物车')
        next('/login');
    }
    else if(to.path=='/pay'){
        alert('请注册或登录，再加入购物车')
        next('/login');
    }
}





})

export default router